<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" layout="horizontal">
        <a-row>
          <a-col :md="6" :sm="24">
            <a-form-item label="状态">
              <a-select
                :allowClear="true"
                :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
                v-model="queryParams.status">
                <a-select-option :value="1">公开</a-select-option>
                <a-select-option :value="2">竞价中</a-select-option>
                <a-select-option :value="3">完成</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="车类型">
              <a-select
                :allowClear="true"
                :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
                v-model="queryParams.chengjiaoLeixing">
                <a-select-option :value="1">商用车</a-select-option>
                <a-select-option :value="2">乘用车</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="竞价状态">
              <a-select
                :allowClear="true"
                :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
                v-model="queryParams.jingjiaStatus">
                <a-select-option :value="1">一次性</a-select-option>
                <a-select-option :value="2">一口价</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <span style="float: right; margin-top: 3px;">
              <a-button type="primary" @click="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="reset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button type="primary" ghost @click="add" v-hasPermission="'vehicle:add'">新增</a-button>
        <!-- <a-button @click="batchDelete" v-hasPermission="'user:delete'">删除</a-button> -->
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
         :columns="columns"
         :dataSource="dataSource"
         :pagination="pagination"
         :loading="loading"
         :scroll="{ x: 3000 }"
         size="small"
         @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{text}}</div>
            </template>
            <p style="width: 150px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="'vehicle:update'" type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修改"></a-icon>
          &nbsp;
          <a-icon v-hasPermission="'vehicle:view'" type="eye" theme="twoTone" twoToneColor="#42b983" @click="view(record)" title="查看"></a-icon>
          <a-badge v-hasNoPermission="'vehicle:update','user:view'" status="warning" text="无权限"></a-badge>
        </template>
      </a-table>
    </div>

    <!-- 查看 -->
    <vehicle-view
      :visible="viewModel.visible"
      :data="viewModel.data"
      @close="handleViewClose"
    >
    </vehicle-view>
    <vehicle-add
      @close="handleAddClose"
      @success="handleAddSuccess"
      :visible="addModel.visible">
    </vehicle-add>
    <!-- 修改用户 -->
    <vehicle-edit
      ref="edit"
      @close="handleEditClose"
      @success="handleEditSuccess"
      :visible="editModel.visible">
    </vehicle-edit>
  </a-card>
</template>

<script>
import RangeDate from '@/components/datetime/RangeDate'
import VehicleAdd from './VehicleAdd'
import VehicleEdit from './VehicleEdit'
import VehicleView from './VehicleView'
import { vehicleFields } from './config.js'
export default {
  name: 'User',
  components: {VehicleAdd, VehicleView, RangeDate, VehicleEdit},
  data () {
    return {
      advanced: false,
      viewModel: {
        visible: false,
        data: {}
      },
      addModel: {
        visible: false
      },
      editModel: {
        visible: false
      },
      queryParams: {},
      filteredInfo: null,
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      selectedRowKeys: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    }
  },
  computed: {
    columns () {
      return vehicleFields
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    handleViewClose () {
      this.viewModel.visible = false
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
      if (!this.advanced) {
        this.queryParams.createTimeFrom = ''
        this.queryParams.createTimeTo = ''
      }
    },
    view (record) {
      this.viewModel.data = record
      this.viewModel.visible = true
    },
    add () {
      this.addModel.visible = true
    },
    handleAddClose () {
      this.addModel.visible = false
    },
    handleAddSuccess () {
      this.addModel.visible = false
      this.$message.success('success')
      this.search()
    },
    edit (record) {
      this.editModel.visible = true
      this.$nextTick(() => {
        this.$refs.edit.setFormValues(record)
      })
    },
    handleEditClose () {
      this.editModel.visible = false
    },
    handleEditSuccess () {
      this.editModel.visible = false
      this.$message.success('success')
      this.search()
    },
    handleDeptChange (value) {
      this.queryParams.deptId = value || ''
    },
    handleDateChange (value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0]
        this.queryParams.createTimeTo = value[1]
      }
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let userIds = []
          for (let key of that.selectedRowKeys) {
            userIds.push(that.dataSource[key].userId)
          }
          that.$delete('user/' + userIds.join(',')).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }

      // 删除掉undefined,以免接口报错
      Object.keys(params).forEach(k => {
        if (params[k] === undefined) {
          delete params[k]
        }
      })
      this.$get('public/pageVehicle', {
        ...params
      }).then((r) => {
        let data = r.data.result
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>
